//
//  CCYNewViewController.m
//  模拟-百思不得姐
//
//  Created by 程春玉 on 16/8/1.
//  Copyright © 2016年 chunyu. All rights reserved.
//

#import "CCYNewViewController.h"
#import "NewListViewController.h"
#import "FriendsListViewController.h"
#import "CCYChatTableViewCell.h"
#import "EMTextMessageBody.h"
#import "LoginViewController.h"
#import <HyphenateFullSDK/EMSDKFull.h>
#import "VideoChatedViewController.h"

@interface CCYNewViewController ()<UITableViewDelegate, UITableViewDataSource, EMClientDelegate, EMCallManagerDelegate>

@property (nonatomic, strong) UITableView *tab;
@property (nonatomic, strong) NSMutableArray *array;
@property (nonatomic,strong) UIImageView *vie;

@end

@implementation CCYNewViewController

- (NSMutableArray *)array
{
    if (!_array) {
        _array = [[[EMClient sharedClient].chatManager loadAllConversationsFromDB] mutableCopy];
    }
    return _array;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.titleView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MainTitle"]];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImage:@"MainTagSubIcon" selectImage:@"MainTagSubIconClick" target:self action:@selector(newBtnClick)];
    self.view.backgroundColor = XMGVColor;
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeSystem)];
    btn.frame = CGRectMake(0, 0, 270, 40);
    btn.center = self.view.center;
    [btn setTitle:@"您还没有登录，登录后即可查看好友列表" forState:(UIControlStateNormal)];
    [btn addTarget:self action:@selector(btnClick) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:btn];
    
    // 注册代理
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    // 视频通话代理
    [[EMClient sharedClient].callManager addDelegate:self delegateQueue:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Action:) name:@"login" object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Action:) name:@"loginOut" object:nil];
}

- (void)Action:(NSNotification *)ation
{
    if ([ation.name isEqualToString:@"login"]) {
        // 注册Cell
        [self createTab];
    } else {
        [self.tab removeFromSuperview];
        self.tab = nil;
    }
}


- (void)viewDidAppear:(BOOL)animated
{
    if ([[EMClient sharedClient] currentUsername] != nil && self.tab == nil) {
        [self createTab];
    } else {
        [self.tab reloadData];
    }
    if (self.view.y != 0) {
        self.tab.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
}

- (void)btnClick
{
    LoginViewController *logVC=[[LoginViewController alloc]init];
    [self presentViewController:logVC animated:YES completion:nil];
}



- (void)createTab
{
    self.tab = [[UITableView alloc] initWithFrame:self.view.frame];
    [self.tab registerNib:[UINib nibWithNibName:@"CCYChatTableViewCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.tab.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"10318878,2560,1600.jpg"]];
    self.tab.contentInset = UIEdgeInsetsMake(64, 0, -44, 0);
    self.tab.dataSource=self;
    self.tab.delegate=self;
    self.tab.rowHeight = 100;
    [self.view addSubview:self.tab];
}


//好友列表
- (void)newBtnClick
{
    FriendsListViewController *FLVC=[[FriendsListViewController alloc]init];
    [self.navigationController pushViewController:FLVC animated:YES];
}
// 账号被挤掉的回调代理
- (void)didLoginFromOtherDevice
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"该账户已在其他地方登录" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [alert addAction:sure];
    [[self.view getCurrentVC] presentViewController:alert animated:YES completion:nil];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tab == nil ? 0 : self.array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    CCYChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    EMConversation *conver = self.array[indexPath.row];
    EMMessage *message = conver.latestMessage;
    if ([message.from isEqualToString:[[EMClient sharedClient] currentUsername]]) {
        cell.name.text = message.to;
    } else {
        cell.name.text = message.from;
    }
    EMMessageBody *body = message.body;
    if (body.type == EMMessageBodyTypeText) {
        cell.message.text = [(EMTextMessageBody *)message.body text];
    } else if (body.type == EMMessageBodyTypeImage) {
        cell.message.text = @"[ 图片 ]";
    } else if (body.type == EMMessageBodyTypeLocation) {
        cell.message.text = @"[ 位置 ]";
    } else if (body.type == EMMessageBodyTypeVoice) {
        cell.message.text = @"[ 语音 ]";
    } else {
        cell.message.text = @"[ 其它 ]";
    }
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewListViewController *NLVC = [[NewListViewController alloc]init];
    EMConversation *conver = self.array[indexPath.row];
    EMMessage *message = conver.latestMessage;
    if ([message.from isEqualToString:[[EMClient sharedClient] currentUsername]]) {
        NLVC.str = message.to;
    } else {
        NLVC.str = message.from;
    }
    [self.navigationController pushViewController:NLVC animated:YES];
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//2、规定编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

//3、提交编辑结果
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CCYChatTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    [[EMClient sharedClient].chatManager deleteConversation:cell.message.text deleteMessages:YES];
    [self.array removeObjectAtIndex:indexPath.row];
    [self.tab reloadData];
}


/*!
 *  用户A拨打用户B，用户B会收到这个回调
 *
 *  @param aSession  会话实例
 */
- (void)didReceiveCallIncoming:(EMCallSession *)aSession
{
    VideoChatedViewController *video = [[VideoChatedViewController alloc] init];
    video.session = aSession;
    [[self.view getCurrentVC] presentViewController:video animated:NO completion:nil];
}

/*!
 *  通话通道建立完成，用户A和用户B都会收到这个回调
 *
 *  @param aSession  会话实例
 */
- (void)didReceiveCallConnected:(EMCallSession *)aSession
{
    NSLog(@"双方视频已接通");
}

/*!
 *  用户B同意用户A拨打的通话后，用户A会收到这个回调
 *
 *  @param aSession  会话实例
 */
- (void)didReceiveCallAccepted:(EMCallSession *)aSession
{
    NSLog(@"%@同意和你进行视频", aSession.username);
}

/*!
 *  1. 用户A或用户B结束通话后，对方会收到该回调
 *  2. 通话出现错误，双方都会收到该回调
 *
 *  @param aSession  会话实例
 *  @param aReason   结束原因
 *  @param aError    错误
 */
- (void)didReceiveCallTerminated:(EMCallSession *)aSession
                          reason:(EMCallEndReason)aReason
                           error:(EMError *)aError
{
    if (aError) {
        NSLog(@"Error:%@", aError);
    } else {
        NSLog(@"结束视频原因:%d", aReason);
    }
}

@end
